import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtGui
from math import *
from numpy import *


class Calculator(QWidget):
    def __init__(self):
        super().__init__()
        # self.setFixedSize(300, 200)
        self.initUI()
        self.records = []
        self.importButton.clicked.connect(self.importFile)
        self.exportButton.clicked.connect(self.exportFile)

    def initUI(self):
        frame = QVBoxLayout()
        self.display = QLineEdit('')
        self.display.setAlignment(Qt.AlignRight)
        font = self.display.font()
        font.setPointSize(font.pointSize() + 8)
        self.display.setFont(font)

        frame.addWidget(self.display)
        grid = QGridLayout()
        grid.setSpacing(5)
        frame.addLayout(grid)
        names = ['(', ')', 'C', '←',
                 '∧', 'log', '√', '/',
                 '7', '8', '9', '*',
                 '4', '5', '6', '-',
                 '1', '2', '3', '+',
                 '.', '0', 'e', '=']

        positions = [(i, j) for i in range(6) for j in range(4)]
        font = QtGui.QFont()
        font.setFamily("Cambria")
        font.setPointSize(17)
        for position, name in zip(positions, names):
            button = QPushButton(name)
            button.setFont(font)
            button.setMinimumHeight(50)
            button.clicked.connect(self.press_btn)
            grid.addWidget(button, *position)

        exportLayout = QHBoxLayout()
        self.importButton = QPushButton('Import')
        self.importButton.setFont(font)
        self.importButton.setMinimumHeight(50)
        self.exportButton = QPushButton('Export')
        self.exportButton.setMinimumHeight(50)
        self.exportButton.setFont(font)
        exportLayout.addWidget(self.importButton)
        exportLayout.addWidget(self.exportButton)
        exportLayout.setSpacing(5)
        frame.addLayout(exportLayout)
        self.setLayout(frame)

    def press_btn(self):
        button_text = self.sender()
        if button_text.text() == 'C':
            self.display.setText('')
        elif button_text.text() == '←':
            self.display.setText(self.display.text()[:-1])
        elif button_text.text() == 'log':
            self.display.setText('log(' + self.display.text() + ')')
        elif button_text.text() == '∧':
            self.display.setText(self.display.text() + '**')
        elif button_text.text() == '√':
            self.display.setText('sqrt(' + self.display.text() + ')')
        elif button_text.text() == '=':
            try:
                res = str(eval(self.display.text()))
                self.records.append(self.display.text() + '=' + res)
                self.display.setText(res)
            except Exception as e:
                QMessageBox.about(self, 'Calculator says ',
                                  'you pass a wrong expression :'+str(e))
        else:
            self.display.setText(self.display.text() + button_text.text())

    def keyPressEvent(self, event):
        if str(event.key()) == '16777220':
            try:
                res = str(eval(self.display.text()))
                self.records.append(self.display.text() + '=' + res)
                self.display.setText(res)
            except Exception as e:
                QMessageBox.about(self, 'Calculator says ',
                                  'you pass a wrong expression :'+str(e))

    def importFile(self):
        openfile_name = QFileDialog.getOpenFileNames(
            self, 'Select the file')
        try:
            out = []
            for line in open(openfile_name[0][0]):
                line = line[:-1] if line[-1] == '\n' else line
                val = eval(line)
                out.append(line + '=' + str(val))
            with open('out.txt', 'w') as f:
                for line in out:
                    f.write(line + '\n')
        except Exception as e:
            QMessageBox.about(self, 'Simple Calculator',
                              'Invalid Input: ' + str(e))

    def exportFile(self):
        try:
            with open('out.txt', 'w') as f:
                for line in self.records:
                    f.write(line + '\n')
            QMessageBox.information(self, 'Simple Calculator',
                                    'Export Successfully!')
        except Exception as e:
            QMessageBox.about(self, 'Simple Calculator',
                              'Export Error: ' + str(e))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    calculator = Calculator()
    calculator.show()
    sys.exit(app.exec_())
